import {useMutation, useQuery, useQueryClient} from "@tanstack/vue-query";
import {roleApi} from "@/api/sys/role.js";
import {computed} from "vue";

// 获取角色列表（分页）
export const useRolePage = (paramsRef) => {
    return useQuery({
        queryKey: computed(() => ["sysRolePage", paramsRef.value]),
        queryFn: () => roleApi.page(paramsRef.value),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
        // 翻页时保持上一次数据
        keepPreviousData: true
    })
}

// 获取全部角色列表
export const useRoleAll = () => {
    return useQuery({
        queryKey: ["sysRoleAll"],
        queryFn: () => roleApi.all(),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
    })
}

// getById
export const useRoleById = (idRef) => {
    return useQuery({
        queryKey: computed(() => ["sysRoleById", idRef.value]),
        queryFn: () => roleApi.getById(idRef.value),
        // 缓存时间5分钟
        staleTime: 5 * 60 * 1000,
        enabled: computed(() => !!idRef.value)
    })
}

export const useSysRoleMutations = () => {
    const queryClient = useQueryClient()

    // 缓存失效统一方法
    const invalidateRoleCaches = async (id) => {
        // 刷新分页列表（可选全量刷新）
        await queryClient.invalidateQueries({queryKey: ['sysRolePage'], exact: false});
        // 刷新全部角色列表
        await queryClient.invalidateQueries({queryKey: ['sysRoleAll'], exact: false});
        // 刷新单条角色详情（如果提供了 id）
        if (id) {
            await queryClient.invalidateQueries({queryKey: ['sysRoleById', id]});
        }
    };

    // create
    const create = useMutation({
        mutationFn: (data) => roleApi.create(data),
        onSuccess: async () => {
            await invalidateRoleCaches();
        },
    });

    // update
    const update = useMutation({
        mutationFn: (data) => roleApi.update(data),
        onSuccess: async (_, data) => {
            await invalidateRoleCaches(data.id);
        },
    });

    // delete /{id}
    const deleteById = useMutation({
        mutationFn: (id) => roleApi.delete(id),
        onSuccess: async (_, id) => {
            await invalidateRoleCaches(id);
        },
    });

    // 批量删除
    const deleteBatch = useMutation({
        mutationFn: (ids) => roleApi.deleteBatch(ids),
        onSuccess: async () => {
            await invalidateRoleCaches();
        },
    });
    return {create, update, deleteById, deleteBatch}
}
